package org.gruposp2p.proyectokarma.controller

import org.gruposp2p.cometd.KarmaMessageService;
import grails.converters.JSON;
import org.gruposp2p.proyectokarma.domain.Peer;
import org.gruposp2p.proyectokarma.domain.Document;
import org.gruposp2p.proyectokarma.domain.Vote;
import org.gruposp2p.proyectokarma.domain.Tag;
import org.gruposp2p.proyectokarma.domain.DocumentTag;
import org.gruposp2p.proyectokarma.domain.Comment;
import org.gruposp2p.proyectokarma.search.SearchHelper;
import java.lang.RuntimeException;

class SearchController {

    SearchHelper searchHelper;

	def index = { }
	
    def document = {
        def documentsMap = new HashMap()
		if (!params.textQuery) {
			render message(code: 'proyectokarma.search.requestWithoutTextMsg')
			return
		}
        List<Document> documents = searchHelper.findByFullText(Document.class,
            ['name', 'content']  as String[], params.textQuery, params.offset, params.max);
        documentsMap.documents = documents.collect {document ->
                return [id: document.id, content: document.content, name:document.name, 
					dateCreated:document.dateCreated, lastUpdate:document.lastUpdated, 
					isPolling:document.polling]
        }
        render documentsMap as JSON
    }
	
	def documentByTag = {
		throw new RuntimeException()
		def documentsMap = new HashMap()
		if (!params.tagName) {
			render message(code: 'proyectokarma.search.requestWithoutTextMsg')
			return
		}
		def selectedTag = Tag.findByName(params.tagName)
		if (selectedTag) {
			documentsMap.documents = DocumentTag.findAllByTag(selectedTag).collect { documentTag ->
				return [id: documentTag.document.id, content: documentTag.document.content, 
					name:documentTag.document.name, dateCreated:documentTag.document.dateCreated, 
					lastUpdate:documentTag.document.lastUpdated, isPolling:documentTag.document.polling]
			} 
		}
		render documentsMap as JSON
	}

	def peer = {
		def peersMap = new HashMap()
		if (!params.textQuery) {
			render message(code: 'proyectokarma.search.requestWithoutTextMsg')
			return
		}
		List<Peer> peers = searchHelper.findByFullText(Peer.class,
			['name']  as String[], params.textQuery, params.offset, params.max);
		peersMap.peers = peers.collect {peer ->
				return [id: peer.id, name:peer.name, username:peer.username, email:peer.email, phone:peer.phone]
		}
		render peersMap as JSON
	}
	
	def comment = {
		def commentsMap = new HashMap()
		if (!params.textQuery) {
			render message(code: 'proyectokarma.search.requestWithoutTextMsg')
			return
		}
		List<Comment> comments = searchHelper.findByFullText(Comment.class,
			['content']  as String[], params.textQuery, params.offset, params.max);
		commentsMap.comments = comments.collect {comment ->
				return [id: comment.id, peer:comment.peerFrom.id, content:comment.content, 
					dateCreated:comment.dateCreated, document:peer.document.id]
		}
		render commentsMap as JSON
	} 
	
}
